<template>
  <div>
    <div class="search">
      <input class="search-input" v-model="searchVal" v-model.trim="searchVal" type="text" placeholder="输入城市名或拼音" />
    </div>
    <div class="search-content search-list" v-show="searchVal">
      <ul>
        <li class="search-item border-bottom" v-for="(item,index) in searchCities" :key="index" @click="handleCityClick(item.name)">
          {{item.name}}
        </li>
        <li class="search-item border-bottom" v-show="!searchCities.length">
          没有找到匹配数据
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
import BScroll from 'better-scroll'
import {mapMutations} from 'vuex'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      searchVal: ''
    }
  },
  computed: {
    searchCities () {
      const searchCities = []
      if (!this.searchVal) {
        // this.searchVal为空 "" 时，为 false
        return searchCities // return语句将终止当前函数并返回当前函数的值
      }
      for (let i in this.cities) {
        this.cities[i].forEach(element => {
          if (
            element.spell.indexOf(this.searchVal) > -1 ||
                        element.name.indexOf(this.searchVal) > -1
          ) {
            searchCities.push(element)
          }
        })
      }
      return searchCities
    }
  },
  methods: {
    handleCityClick (city) {
      // this.$store.dispatch('changeCity', city)
      // this.$store.commit('changeCity', city)
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  mounted () {
    setTimeout(() => {
      this.scroll = new BScroll('.search-list', {click: true})
    }, 20)
  }
}
</script>

<style lang="stylus" scoped>
.search {
  height: 0.72rem;
  padding: 0 0.1rem;
  background: #00bcd4;

  .search-input {
    box-sizing: border-box;
    width: 100%;
    height: 0.62rem;
    padding: 0 0.1rem;
    line-height: 0.62rem;
    text-align: center;
    border-radius: 0.06rem;
    color: #666;
  }
}

.search-content {
  z-index: 1;
  overflow: hidden;
  position: absolute;
  top: 1.58rem;
  left: 0;
  right: 0;
  bottom: 0;
  background: #eee;

  .search-item {
    line-height: 0.62rem;
    padding-left: 0.2rem;
    background: #fff;
    color: #666;
  }
}
</style>
